import { kycForm } from "@/forms"
import { createLogger } from "@/utils/logger"
import { css } from "@emotion/react"
import { useMemo } from "react"
import { FieldPath } from "react-hook-form"

const logger = createLogger("BaseFormField")
type FormValues = typeof kycForm._type.FormValues

type Props<K extends FieldPath<FormValues>> = typeof kycForm.BaseItem<K> extends (
    props: infer P,
) => React.ReactNode
    ? P
    : never

export default function BaseFormField<K extends FieldPath<FormValues>>(props: Props<K>) {
    const form = kycForm.useFormContext()
    const errorMessage = useMemo(() => {
        const error = form.formState.errors[props.field as keyof typeof form.formState.errors]
        if (!error) return null
        return error.message
    }, [form, props.field])

    return (
        <div
            css={css`
                display: flex;
                flex-direction: column;
                align-items: stretch;
                justify-content: flex-start;
                gap: 8rem;
            `}
        >
            <div
                css={css`
                    font-weight: 600;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                `}
            >
                {props.label}
            </div>
            <kycForm.BaseItem {...props} />
            <div
                css={css`
                    transition: opacity 0.2s ease-in-out;
                    opacity: ${errorMessage ? 1 : 0};
                    font-weight: 500;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                    color: #ff0000;
                `}
            >
                {errorMessage}
            </div>
        </div>
    )
}
